<?php
namespace App\ViewComposers;

use App\Admin\Models\Menu;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use DB;
use Illuminate\Support\Facades\Log;

class MenuComposer {

    /**
     * The user repository implementation.
     *
     * @var UserRepository
     */
    protected $menus;

    /**
     * Create a new profile composer.
     *
     * @param  UserRepository  $users
     * @return void
     */
    public function __construct()
    {
        $firstLevel = Menu::where(['pid'=>0])->get();
        $res = array();
        if($firstLevel) {
            foreach ($firstLevel as $value) {
                $temp= array(
                    'name'=>$value->name,
                    'tag'=>$value->tag,
                    'link'=>$value->link
                );
                $secondlevel = Menu::where(['pid'=>$value->id])->get();
                if($secondlevel) {
                    $temp['sub'] = array();
                    foreach($secondlevel as $v) {
                        $temp['sub'][] = array(
                            'name'=>$v->name,
                            'link'=>$v->link
                        );
                    }
                }
                $res[] = $temp;
            }
        }
        $this->menus = $res;
        Log::info(var_export($res,true));
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('menus', $this->menus);
    }

}